import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';

export interface IndexModelState {
    name: number;
}

export interface IndexModelType {
    namespace: 'about';
    state: IndexModelState;
    reducers: {
        // add: Reducer<IndexModelState>;
        // 启用 immer 之后
        add: ImmerReducer<IndexModelState>;
    };
      effects: {
        query: Effect;
      };

      subscriptions: { setup: Subscription };
}

const IndexModel: IndexModelType = {
    namespace: 'about',

    state: {
        // 数组 []
        name: 6666666,
    },

    // state: [1, 2, 3]
    reducers: {
        // add(state, action) {
        //     state.name = 1 
        //     return { ...state, ...action.payload }
        // },
        add(state, action) {
            //   console.log(Array.from(state))
            state = { ...state }
            state.name += 1
            return {
                ...state
            }
        },

        // save(state, action) {
        //     return {
        //         ...state,
        //         ...action.payload,
        //     };
        // },
    },
    effects: {
        *query(action, { put }) { 
            console.log(action)
            yield setTimeout((res) => {
                put({ type: "add" })
            }, 100)
        },
    },

      subscriptions: {
        setup({ dispatch, history }) {
          return history.listen(({ pathname }) => {
            if (pathname === '/') {
              dispatch({
                type: 'query',
              });
            }
          });
        },
      },
};

export default IndexModel;